//
//  SetTimeViewController.m
//  ForestPack
//
//  Created by 郑洲 on 2018/7/29.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "SetTimeViewController.h"

@interface SetTimeViewController ()<UITableViewDelegate, UITableViewDataSource>{
    UIButton *shadowBtn;
}

@property (nonatomic, strong) BaseTableView *tableView;

@property (nonatomic, strong) UISwitch *acceptSwitch;
@property (nonatomic, strong) UISwitch *systemSwitch;
@property (nonatomic, strong) NSMutableArray *timeArr;

@property (nonatomic, strong) UIDatePicker *dataPicker;
@property (nonatomic, strong) UIView *pickViewToobar;//pickview的完成工具条
@property (nonatomic, assign) NSInteger selectState;

@property (nonatomic, copy)   NSString *selectTime;

@end

@implementation SetTimeViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self setLeftButton:[UIImage imageNamed:@"返回白色"] title:nil target:self action:@selector(backClick) rect:CGRectMake(0, 0, 44, 44)];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"系统接单";
    self.timeArr = [NSMutableArray arrayWithArray:_shopInfo.times];
    [self.timeArr addObject:[NSMutableDictionary dictionaryWithDictionary:@{@"start_time":@"",@"end_time":@""}]];
    
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}

- (void)backClick {
    [HttpManager showWaitMsg:@"保存设置"];
    NSString *startTime = @"";
    NSString *endTime = @"";
    for (int i = 0; i < self.timeArr.count; i++) {
        NSDictionary *dic = self.timeArr[i];
        if ([dic[@"start_time"] length] > 0 && [dic[@"end_time"] length] > 0) {
            startTime = [startTime stringByAppendingString:[NSString stringWithFormat:@",%@",dic[@"start_time"]]];
            endTime = [endTime stringByAppendingString:[NSString stringWithFormat:@",%@",dic[@"end_time"]]];
        }
    }
    if (startTime.length > 0) {
        startTime = [startTime substringFromIndex:1];
        endTime = [endTime substringFromIndex:1];
    }
    NSString *url = [NSString stringWithFormat:@"%@app/shop_update_time",REQUESTHEADER];
    NSDictionary *dict = @{@"token":[FPLoginAndRegisterTools getToken],@"shop_id":_shopInfo.Id,@"start_time":startTime,@"end_time":endTime,@"is_receipt":[NSNumber numberWithBool:_acceptSwitch.isOn],@"is_system":[NSNumber numberWithBool:_systemSwitch.isOn]};

    [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [HttpManager hideWait];
            [HttpManager showNoteMsg:@"保存成功"];
            NSNotification *notification = [[NSNotification alloc]initWithName:@"ReloadShop" object:nil userInfo:nil];
            [[NSNotificationCenter defaultCenter] postNotification:notification];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2 + _timeArr.count;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        static NSString *cellId = @"headCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            NSArray *arr = @[@"是否接单",@"系统接单"];
            
            UIView *note_line = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(15), ScreenX375(3), ScreenX375(23))];
            note_line.backgroundColor = ThemeColor;
            [cell addSubview:note_line];
            
            UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(15), ScreenX375(150), ScreenX375(24))];
            noteLabel.text = arr[indexPath.section];
            noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
            noteLabel.font = Kfont(18);
            [cell addSubview:noteLabel];
            
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(53) - 0.5, SCREEN_WIDTH, 0.5)];
            line.backgroundColor = LineColor;
            [cell addSubview:line];
            
            UISwitch *cSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - ScreenX375(63), ScreenX375(11), ScreenX375(50), ScreenX375(30))];
            [cSwitch addTarget:self action:@selector(changeStatus:) forControlEvents:UIControlEventValueChanged];
            if (indexPath.section == 0) {
                _acceptSwitch = cSwitch;
                [_acceptSwitch setOn:[_shopInfo.is_receipt integerValue]];
            }else {
                _systemSwitch = cSwitch;
                _systemSwitch.enabled = _acceptSwitch.isOn;
                [_systemSwitch setOn:[_shopInfo.is_system integerValue]];
            }
            [cell addSubview:cSwitch];
        }
        return cell;
    }else if (indexPath.row == 1) {
        static NSString *cellId = @"noteCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        for (UIView *subView in cell.subviews) {
            [subView removeFromSuperview];
        }
        UIImageView *selectImg = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(21), ScreenX375(14), ScreenX375(14))];
        [cell addSubview:selectImg];
        
        UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(38), ScreenX375(20), ScreenX375(100), ScreenX375(18))];
        noteLabel.text = @"时间段控制";
        noteLabel.font = Kfont(16);
        [cell addSubview:noteLabel];
        if (_acceptSwitch.isOn) {
            selectImg.image = ImageWithName(@"椭圆1拷贝5");
            noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
        }else {
            selectImg.image = ImageWithName(@"圆角矩形6拷贝3");
            noteLabel.textColor = REXADECIMALCOLOR(@"#dcdcdc");
        }
        return cell;
    }else {
        static NSString *cellId = @"timeCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        for (UIView *subView in cell.subviews) {
            [subView removeFromSuperview];
        }
        UIButton *startBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(38), 0, ScreenX375(94), ScreenX375(30))];
        [startBtn setTitle:_timeArr[indexPath.row - 2][@"start_time"] forState:UIControlStateNormal];
        if (_acceptSwitch.isOn) {
            [startBtn setTitleColor:FONTCOLOR_BLACK forState:UIControlStateNormal];
        }else {
            [startBtn setTitleColor:FONTCOLOR_LIGHTGRAY forState:UIControlStateNormal];
        }
        startBtn.titleLabel.font = Kfont(14);
        startBtn.layer.borderColor = REXADECIMALCOLOR(@"#dcdcdc").CGColor;
        startBtn.layer.borderWidth = 0.5;
        startBtn.layer.cornerRadius = ScreenX375(15);
        startBtn.clipsToBounds = YES;
        startBtn.enabled = _acceptSwitch.isOn;
        startBtn.tag = 100 + indexPath.row - 2;
        [startBtn addTarget:self action:@selector(selectTime:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:startBtn];
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(ScreenX375(142), ScreenX375(14.5), ScreenX375(16), ScreenX375(1))];
        line.backgroundColor = LineColor;
        [cell addSubview:line];
        
        UIButton *endBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(167), 0, ScreenX375(94), ScreenX375(30))];
        [endBtn setTitle:_timeArr[indexPath.row - 2][@"end_time"] forState:UIControlStateNormal];
        if (_acceptSwitch.isOn) {
            [endBtn setTitleColor:FONTCOLOR_BLACK forState:UIControlStateNormal];
        }else {
            [endBtn setTitleColor:FONTCOLOR_LIGHTGRAY forState:UIControlStateNormal];
        }
        endBtn.titleLabel.font = Kfont(14);
        endBtn.layer.borderColor = REXADECIMALCOLOR(@"#dcdcdc").CGColor;
        endBtn.layer.borderWidth = 0.5;
        endBtn.layer.cornerRadius = ScreenX375(15);
        endBtn.clipsToBounds = YES;
        endBtn.enabled = _acceptSwitch.isOn;
        endBtn.tag = 200 + indexPath.row - 2;
        [endBtn addTarget:self action:@selector(selectTime:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:endBtn];
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return ScreenX375(53);
    }else if (indexPath.row == 1) {
        return ScreenX375(52);
    }
    return ScreenX375(45);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return ScreenX375(10);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(10))];
    view.backgroundColor = TABLEVIEW_BACKGROUNDCOLOR;
    return view;
}

- (void)changeStatus:(UISwitch *)cSwitch {
    if (cSwitch == _acceptSwitch) {
        _systemSwitch.enabled = _acceptSwitch.isOn;
        if (!_acceptSwitch.isOn) {
            [_systemSwitch setOn:NO];
        }
        [self.tableView reloadData];
    }
}

- (void)selectTime:(UIButton *)button {
    _selectState = button.tag;
    if (!shadowBtn) {
        shadowBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        shadowBtn.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        [shadowBtn addTarget:self action:@selector(hiddenPickView) forControlEvents:UIControlEventTouchUpInside];
        shadowBtn.hidden = YES;
        [self.view addSubview:shadowBtn];
    }
    if (!_pickViewToobar) {
        [self setPickerToobar];
    }
    if (!_dataPicker) {
        _dataPicker = [[UIDatePicker alloc] init];
        _dataPicker.frame = CGRectMake(0,CGRectGetMaxY(_pickViewToobar.frame), SCREEN_WIDTH, SCREEN_WIDTH / 375 * 260 - 44); // 设置显示的位置和大小
        _dataPicker.date = [NSDate date]; // 设置初始时间
        _dataPicker.backgroundColor = [UIColor whiteColor];
        _dataPicker.timeZone = [NSTimeZone timeZoneWithName:@"GTM+8"]; // 设置时区，中国在东八区
        _dataPicker.datePickerMode = UIDatePickerModeTime; // 设置样式
        [_dataPicker addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged]; // 添加监听器
        [self.view addSubview:_dataPicker];
    }
    //判断pickerView的位置
    if (_dataPicker.frame.origin.y == SCREEN_HEIGHT+44) {
        
        [UIView animateWithDuration:0.3 animations:^{
            self->shadowBtn.hidden = NO;
            self.dataPicker.frame = CGRectMake(0, SCREEN_HEIGHT - (SCREEN_HEIGHT + NAVIGATION_BAR_HEIGHT) / 2.5 + 44, SCREEN_WIDTH, (SCREEN_HEIGHT + NAVIGATION_BAR_HEIGHT) / 2.5 - 44);
            self.pickViewToobar.frame = CGRectMake(0,CGRectGetMinY(self.dataPicker.frame)-44, SCREEN_WIDTH, 44);
            
        }];
        
    }else{
        
        [UIView animateWithDuration:0.3 animations:^{
            self->shadowBtn.hidden = YES;
            self.pickViewToobar.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 44);
            self.dataPicker.frame = CGRectMake(0, CGRectGetMaxY(self.pickViewToobar.frame), SCREEN_WIDTH, (SCREEN_HEIGHT + NAVIGATION_BAR_HEIGHT) / 2.5 - 44);
        }];
    }
}

//点击pickView的工具条操作按钮
- (void)pickViewOperateClick:(UIButton *)sender{
    
    if (sender.tag == 1) {
        //完成
        [self hiddenPickView];
        if (_selectState >= 200) {
            [self.timeArr[_selectState - 200] setValue:_selectTime forKey:@"end_time"];
        }else {
            [self.timeArr[_selectState - 100] setValue:_selectTime forKey:@"start_time"];
        }
        NSInteger isNUll = 0;
        for (NSDictionary *dic in self.timeArr) {
            for (NSString *str in dic.allValues) {
                if (str.length == 0) {
                    isNUll = 1;
                }
            }
        }
        if (isNUll == 0) {
            [self.timeArr addObject:[NSMutableDictionary dictionaryWithDictionary:@{@"start_time":@"",@"end_time":@""}]];
        }
        [self.tableView reloadData];
    }else{
        //取消
        [self hiddenPickView];
        _selectTime = @"";
    }
}

- (void)datePickerValueChanged:(UIDatePicker *) sender {
    
    NSDate *select = [sender date]; // 获取被选中的时间
    NSDateFormatter *selectDateFormatter = [[NSDateFormatter alloc] init];
    selectDateFormatter.dateFormat = @"HH:mm"; // 设置时间和日期的格式
    _selectTime = [selectDateFormatter stringFromDate:select]; // 把date类型转为设置好格式的string类型
}

- (void)setPickerToobar {
    //工具条
    _pickViewToobar = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 44)];
    _pickViewToobar.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_pickViewToobar];
    
    for (int i = 0; i < 2; i++) {
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, i * 43.5, SCREEN_WIDTH, 0.5)];
        line.backgroundColor = LineColor;
        [_pickViewToobar addSubview:line];
    }
    
    UIButton *cancleBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 0, 40, _pickViewToobar.frame.size.height)];
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancleBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
    [cancleBtn addTarget:self action:@selector(pickViewOperateClick:) forControlEvents:UIControlEventTouchUpInside];
    [_pickViewToobar addSubview:cancleBtn];
    
    UIButton *achiveBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 50, 0, 40, _pickViewToobar.frame.size.height)];
    [achiveBtn setTitle:@"完成" forState:UIControlStateNormal];
    achiveBtn.tag = 1;
    [achiveBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
    [achiveBtn addTarget:self action:@selector(pickViewOperateClick:) forControlEvents:UIControlEventTouchUpInside];
    [_pickViewToobar addSubview:achiveBtn];
}


- (void)hiddenPickView{
    
    [UIView animateWithDuration:0.3 animations:^{
        self->shadowBtn.hidden = YES;
        self.pickViewToobar.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 44);
        self.dataPicker.frame = CGRectMake(0, CGRectGetMaxY(self.pickViewToobar.frame), SCREEN_WIDTH, (SCREEN_HEIGHT + NAVIGATION_BAR_HEIGHT) / 2.5);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
